package com.jdwx.opengl.kotlin

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlin.system.measureTimeMillis

//fun main() = runBlocking {
//    val numbers = produceNumbers() // 从 1 开始生产整数
//    val squares = square(numbers) // 对整数做平方
//    for (i in 1..5) println(squares.receive()) // 打印前 5 个数字
//    println("Done!") // 我们的操作已经结束了
//    coroutineContext.cancelChildren() // 取消子协程
//}
//
//fun CoroutineScope.produceNumbers() = produce<Int> {
//    var x = 1
//    while (x<20) send(x++) // 从 1 开始的无限的整数流
//}
//
//fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce {
//    println("=============")
//    for (x in numbers){
//        send(x * x)
//        println("x=$x")
//    }
//    println("=============")
//}

//
//fun main() = runBlocking {
//    val handler = CoroutineExceptionHandler { _, exception ->
//        println("Caught $exception")
//    }
//    val job = GlobalScope.launch(handler) {
//        launch { // 第一个子协程
//            try {
//                delay(Long.MAX_VALUE)
//            } finally {
//                withContext(NonCancellable) {
//                    println("Children are cancelled, but exception is not handled until all children terminate")
//                    delay(2000)
//                    println("The first child finished its non cancellable block")
//                }
//            }
//        }
//        launch { // 第二个子协程
//            delay(10)
//            println("Second child throws an exception")
//            throw ArithmeticException()
//        }
//    }
//    job.join()
//}

suspend fun massiveRun(action: suspend () -> Unit) {
    val n = 100  // 启动的协程数量
    val k = 1000 // 每个协程重复执行同一动作的次数
    val time = measureTimeMillis {
        coroutineScope { // 协程的作用域
            repeat(n) {
                launch {
                    repeat(k) { action() }
                }
            }
        }
    }
    println("Completed ${n * k} actions in $time ms")
}

var counter = 0
var xiaobai = 0
fun a(ab:()->Unit){
    ab()
}

fun main() = runBlocking {
    withContext(Dispatchers.Default) {
        massiveRun {
            counter++
        }
    }
    println("Counter = $counter")


    a{xiaobai++}


    println("xiaobai=="+xiaobai)

}